/*
 *
 * @ProjectName:    my_umi_app
 * @Package:
 * @ClassName:      color_widget
 * @Description:    颜色选择器封装
 * @Author:         SuPeiSen
 * @CreateDate:     2021/1/20 11:12 上午
 * @UpdateDate:     2021/1/20 11:12 上午
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */

import React, { useState } from 'react';
import './style.less';
import { SketchPicker, RGBColor, ColorResult } from 'react-color';
import { useOnOutsideClick } from '@/app_hook/useOnOutsideClick';

export const ColorWidget = (props: {
  selectColor?: (color: RGBColor) => void;
  initColor?: RGBColor;
}) => {
  const defaultColor: RGBColor = props.initColor ?? { b: 0, g: 0, r: 0, a: 1 };
  const [color, setColor] = useState<RGBColor>(defaultColor);
  const [displayColorPicker, setDisplayColorPicker] = useState<boolean>(false);

  const { innerBorderRef } = useOnOutsideClick<HTMLDivElement>(() =>
    setDisplayColorPicker(false),
  );

  const bgColor = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})`;

  const colorOnChange = (value: ColorResult) => {
    setColor(value.rgb);
    if (props?.selectColor != null) {
      props.selectColor(value.rgb);
    }
  };

  return (
    <div style={{ display: 'flex' }}>
      {displayColorPicker ? (
        <div ref={innerBorderRef}>
          <SketchPicker onChange={colorOnChange} color={color} />
        </div>
      ) : (
        <div
          onClick={() => setDisplayColorPicker(true)}
          className="show_color_box"
          style={{ backgroundColor: bgColor }}
        ></div>
      )}
    </div>
  );
};
